package com.gaowl.yygh.hosp.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gaowl.yygh.commom.exception.HospitalException;
import com.gaowl.yygh.commom.result.ResultCodeEnum;
import com.gaowl.yygh.hosp.repository.ScheduleRepository;
import com.gaowl.yygh.hosp.service.DepartmentService;
import com.gaowl.yygh.hosp.service.HospitalService;
import com.gaowl.yygh.hosp.service.ScheduleService;
import com.gaowl.yygh.model.hosp.BookingRule;
import com.gaowl.yygh.model.hosp.Department;
import com.gaowl.yygh.model.hosp.Hospital;
import com.gaowl.yygh.model.hosp.Schedule;
import com.gaowl.yygh.vo.hosp.BookingScheduleRuleVo;
import com.gaowl.yygh.vo.hosp.ScheduleOrderVo;
import com.gaowl.yygh.vo.hosp.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    // 保存排班信息
    @Override
    public void save(Map<String, Object> paramMap) {
        // paramMap 转换department对象
        String paramMapString = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(paramMapString,Schedule.class);

        // 根据医院编号 和 排班编号查询排班信息
        Schedule scheduleExist = scheduleRepository.
                getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(),schedule.getHosScheduleId());
        // 若存在排班，则更新；否则新建排班信息
        if(scheduleExist!=null) {
            scheduleExist.setUpdateTime(new Date());
            scheduleExist.setIsDeleted(0);
            scheduleExist.setStatus(1);
            scheduleRepository.save(scheduleExist);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(schedule);
        }
    }

    // 移除排班信息
    @Override
    public void remove(String hoscode, String hosScheduleId) {
        // 先根据 医院编号 和 排班编号 查询排班信息
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if(schedule != null) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    // 查询排班信息（医院api用）
    @Override
    public Page<Schedule> findPageSchedule(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        // 1.创建Pageable对象，设置当前页和每页记录数
        Pageable pageable = PageRequest.of(page-1,limit);

        // 2.创建Example对象
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo,schedule);
        schedule.setIsDeleted(0);
        schedule.setStatus(1);

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Schedule> example = Example.of(schedule,matcher);

        // 3.调用MongoRepository中的方法，查询排班信息
        Page<Schedule> all = scheduleRepository.findAll(example, pageable);
        return all;
    }

    // 查询排班信息（根据医院的hoscode和科室的depcode）
    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {
        // 构建查询条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);

         Aggregation agg = Aggregation.newAggregation(
                // 1.根据医院编号和科室编号查询排班信息
                Aggregation.match(criteria),

                // 2.根据工作日期WorkDate进行分组，并统计号源数量
                Aggregation.group("workDate")
                .first("workDate").as("workDate")
                .count().as("docCount")
                .sum("reservedNumber").as("reservedNumber")
                .sum("availableNumber").as("availableNumber"),

                // 3.根据工作日期降序排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),

                // 4.分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );

        // 调用方法，最终执行上述一系列操作，获取排班信息
        AggregationResults<BookingScheduleRuleVo> aggResults =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResults.getMappedResults();

        // 获取分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();

        // 获取排班信息中的日期，转换为周几的形式，添加到排班信息中
        for(BookingScheduleRuleVo bookingScheduleRuleVo: bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();  // 获取日期
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate)); // 转换为星期几
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);  // 设置属性
        }

        // 设置最终数据，进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList",bookingScheduleRuleVoList);
        result.put("total",total);  // 排班总记录数

        // 将医院名称添加到数据中
        String hosname = hospitalService.getHospName(hoscode);
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosname);

        result.put("baseMap",baseMap);

        return result;
    }

    /**
    * 根据医院编号、科室编号和工作日期，查询详细的排班信息
    */
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        // 查询
        List<Schedule> scheduleList = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());  // 日期原为字符串，需进行转换
        // 向结果中添加医院名称、科室名称、日期对应星期等信息
        scheduleList.forEach(this::packageSchedule);

        return scheduleList;
    }

    //封装排班详情其他值 医院名称、科室名称、日期对应星期
    private Schedule packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname",hospitalService.getHospName(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname",departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        return schedule;
    }

    /**
     * 根据日期获取周几数据
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    /**
    * @Description: 查询 可预约的排班 信息
    * @Param hoscode,depcode   医院代码,科室代码
    *          page,limit       当前页，每页多少数据
    * @return: 可预约的排班信息
    */
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        Map<String, Object> result= new HashMap<>();

        // 获取医院及其预约规则
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        if (hospital == null) {
            throw new HospitalException(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();

        // 根据预约规则，获取当前可预约日期
        IPage<Date> iPage = this.getListDate(page, limit, bookingRule);
        List<Date> dateList = iPage.getRecords();

        // 获取当前医院当前科室 在可预约日期的 剩余可预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode)
                .and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate").first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregateResult =  mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList = aggregateResult.getMappedResults();

        // 合并数据 将统计数据ScheduleVo根据“排班日期”合并到BookingRuleVo
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(scheduleVoList)) {   // 可预约排班 非空
            scheduleVoMap = scheduleVoList.stream().collect(
                    Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }

        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for(int i=0, len=dateList.size(); i<len; i++) {
            Date date = dateList.get(i);   // 当前排班日期
            // ============= 开始设置可预约排班规则数据 ===============
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            if (null == bookingScheduleRuleVo) { // 当前无预约排班
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                bookingScheduleRuleVo.setDocCount(0);  //就诊医生人数
                bookingScheduleRuleVo.setAvailableNumber(-1);  //科室剩余预约数, -1表示无号
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));  // 计算当前预约日期为周几
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            if (i == len - 1 && page == iPage.getPages()) {  //最后一页最后一条记录为即将预约
                bookingScheduleRuleVo.setStatus(1);  // 状态 0：正常, 1：即将放号, -1：当天已停止挂号
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }

            if (i == 0 && page == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    System.out.println("测试用");
                    //bookingScheduleRuleVo.setStatus(-1);  // 当天预约如果过了停号时间， 不能预约
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
            // ============= 结束设置可预约排班规则数据 ===============
        }

        result.put("bookingScheduleRuleVoList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hospitalService.getHospName(hoscode)); //医院名称
        Department department =departmentService.getDepartment(hoscode, depcode);  //科室
        baseMap.put("bigname", department.getBigname());  //大科室名称
        baseMap.put("depname", department.getDepname()); //科室名称
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));  //月
        baseMap.put("releaseTime", bookingRule.getReleaseTime()); //放号时间
        baseMap.put("stopTime", bookingRule.getStopTime());  //停号时间
        result.put("baseMap", baseMap);
        System.out.println(result);
        return result;
    }

    private IPage<Date> getListDate(int page, int limit, BookingRule bookingRule) {
        //当天放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //预约周期
        int cycle = bookingRule.getCycle();
        //如果当天放号时间已过，则预约周期后一天为即将放号时间，周期加1
        if(releaseTime.isBeforeNow()) cycle += 1;
        //可预约所有日期，最后一天显示即将放号倒计时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            //计算当前预约日期
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
        //日期分页，由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        List<Date> pageDateList = new ArrayList<>();
        int start = (page-1)*limit;
        int end = (page-1)*limit+limit;
        if(end >dateList.size()) end = dateList.size();
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, 7, dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }

    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        return DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
    }




    // 根据排班id获取排班数据
    @Override
    public Schedule getScheduleId(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        return this.packageSchedule(schedule);
    }

    /**
    * @Description: 根据排班id获取 预约订单数据
    * @param scheduleId: 排班id
    * @return: 预约订单实体类
    */
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();

        // 根据排班id获取排班信息
        Schedule schedule = this.getScheduleId(scheduleId);
        if(schedule == null) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        // 获取对应医院的预约规则信息
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        if(hospital == null) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        if(bookingRule == null) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }

        // 设置scheduleOrderVo
        scheduleOrderVo.setHoscode(schedule.getHoscode());    // 医院代码
        scheduleOrderVo.setHosname(hospitalService.getHospName(schedule.getHoscode()));  // 医院名称
        scheduleOrderVo.setDepcode(schedule.getDepcode());  // 科室代码
        scheduleOrderVo.setDepname(departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));  // 科室名称
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());   // 排班编号
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());   // 可预约数
        scheduleOrderVo.setTitle(schedule.getTitle());  // 职称
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());  // 排班日期
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());  // 排班时间（上下午）
        scheduleOrderVo.setAmount(schedule.getAmount());   // 挂号费

        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());   // 退号截止天数（如：就诊前一天为-1，当天为0）

        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());   // 预约开始时间

        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());        // 预约截止时间

        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());    // 当天停止挂号时间

        return scheduleOrderVo;
    }


    /**
     * @Description: 更新排班信息（用于RabbitMQ）
     * @param schedule: 排班信息
     */
    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }
}
